
    /**  
    * @Title: QueryStringUtil.java
    * @Package com.efast.cafe.framework.util
    * @Description: TODO(用一句话描述该文件做什么)
    * @author Administrator
    * @date 2018年8月22日
    * @version V1.0  
    */
    
package com.efast.cafe.framework.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.reflect.Field;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.efast.cafe.util.StringUtil;

/**
    * @ClassName: QueryStringUtil
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @author Administrator
    * @date 2018年8月22日
    *
    */

public class QueryStringUtil {
	private final static String EMPTY_STR = "";
	public static final String DFT_DELIMITER = "|";
	public static final String DFT_NUMBER = "0";
	public static final Boolean isOracle = false;
	    /**
	     * check the str if it's empty (null or '').
	     *
	     * @param str
	     * @return
	     */
	    public static boolean isEmpty(String str) {
	    	return StringUtils.isBlank(str);
	    }
	    
	    public static boolean isNumeric(String str){ 
				if (StringUtil.isEmpty(str)) {
					return false; 
				}
	    	   Pattern pattern = Pattern.compile("[0-9]*"); 
	    	   Matcher isNum = pattern.matcher(str);
	    	   if(isNum.matches()){
	    	       return true; 
	    	   } 
	    	   return false; 
	    }
	    /**
	     * capitalize the first letter of word
	     *
	     * @param str
	     * @return
	     */
	    public static String capitalize(String str) {
	    	return StringUtils.capitalize(str);
	    }

	    /**
	     * uncapitalize the first letter of word
	     *
	     * @param str
	     * @return
	     */
	    public static String uncapitalize(String str) {
	        return StringUtils.uncapitalize(str);
	    }

	    public static String escapeHtml(String in) {
	        if (StringUtils.isBlank(in)) {
	            return in;
	        }

	        return StringEscapeUtils.escapeHtml(in);
	    }

	    public static String escapeJavascript(String in) {
	        if (StringUtils.isBlank(in)) {
	            return "";
	        }

	        return StringEscapeUtils.escapeJavaScript(in);
	    }

	    /**
	     * target should be string or number
	     * source can be array, list or string splitted by '|'
	     * @param target
	     * @param source
	     * @return
	     */
	    public static boolean isIn(Object target, Object source) {
	        if (target == null || source == null) {
	            return false;
	        }

	        if (source instanceof Object[]) {
	            Object[] sources = (Object[]) source;
	            for (Object object : sources) {
	                if (object == null) {
	                    continue;
	                }
	                if (object.toString().equals(target.toString())) {
	                    return true;
	                }
	            }
	        } else if (source instanceof List<?>) {
	            List<?> sources = (List<?>) source;
	            for (Object object : sources) {
	                if (object == null) {
	                    continue;
	                }
	                if (object.toString().equals(target.toString())) {
	                    return true;
	                }
	            }
	        } else {
	            String[] sources = source.toString().split("\\|");
	            for (String object : sources) {
	                if (object == null) {
	                    continue;
	                }
	                if (object.equals(target.toString())) {
	                    return true;
	                }
	            }
	        }
	        return false;
	    }

	    public static String arrayToString(Object[] array) {
	    	if (array == null || array.length == 0) {
	            return null;
	        }

	        StringBuffer sb = new StringBuffer();
	        for (int i = 0; i < array.length; i++) {
	            sb.append(array[i].toString());
	            if (i != (array.length - 1)) {
	                sb.append(DFT_DELIMITER);
	            }
	        }

	        return sb.toString();
	    }

	    /**
	     * return '-' if input string is null or '', otherwise input string.
	     *
	     * @param in
	     * @return
	     */
	    public static String getNonEmpty(String in) {
	        String out = EMPTY_STR;
	        if (!isEmpty(in)) {
	            out = in;
	        }
	        return out;
	    }

	    /**
	     * return '' if input string is null, otherwise input string.
	     *
	     * @param in
	     * @return
	     */
	    public static String getNonNull(String in) {
	        String out = "";
	        if (!isEmpty(in)) {
	            out = in;
	        }
	        return out;
	    }

	    public static boolean isDigit(String str) {
	    	return NumberUtils.isDigits(str);
	    }
	    
	    public static boolean isValidNumber(String str) {
	    	if (NumberUtils.isNumber(str) && str.contains(".")) {
	    		str = str.replace("-", "");
	    		char[] array = str.split("\\.")[0].toCharArray();
	    		if (48 == (byte)array[0]) {
	    			if (array.length > 1) {
	    				return false;
	        		} else {
	        			return true;
	        		}
	    		}
	    	}
	    	
	    	return NumberUtils.isNumber(str);
	    }

	    /**
	     * return sub-string of input string. by default first 120 characters.
	     *
	     * @param desc
	     * @return
	     */
	    public static String getShortDesc(String desc) {
	        return getShortDesc(desc, 72);
	    }

	    public static String getShortDesc(String desc, int size) {
	        if (isEmpty(desc))
	            return null;

	        if (desc.length() > size) {
	            return desc.substring(0, size) + "...";
	        }
	        return desc;
	    }

	    public static String[] cut(final String in, final int length) {
	        if (isEmpty(in))
	            return null;

	        int size = (int) Math.ceil(((double) in.length() / length));
	        String[] out = new String[size];
	        for (int i = 0; i < size; i++) {
	            int from = i * length;
	            int to = (i + 1) * length;
	            if (to > in.length()) {
	                to = in.length();
	            }
	            out[i] = in.substring(from, to);
	        }
	        return out;
	    }

	    public static String replaceLast(String text, String regex, String replacement) {
	        if (isEmpty(text) || isEmpty(regex)) {
	            return text;
	        }

	        return text.replaceFirst("(?s)" + regex + "(?!.*?" + regex + ")", getNonNull(replacement));
	    }

	    public static String showTextArea(String val) {
	        return getNonNull(escapeHtml(val)).replaceAll("\r\n", "<br/>").replaceAll("\r", "<br/>").replaceAll("\n", "<br/>");
	    }
	    public static String formatTime(){
	    	SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddhh");
	    	return sf.format(new Date());    	
	    }
	    /**
	     * 产生4位随机数(0000-9999)
	     * @return 4位随机数
	     */
	    public static String getFourRandom(){
	        Random random = new Random();
	        String fourRandom = random.nextInt(10000) + "";
	        int randLength = fourRandom.length();
	        if(randLength<4){
	          for(int i=1; i<=4-randLength; i++)
	              fourRandom = "0" + fourRandom  ;
	      }
	        return fourRandom;
	    }
	    public static String contractBindSql(String entity,String key) {
			if (StringUtil.isEmpty(key)) {
				return "";
			}
			return StringUtil.isEmpty(entity) ? key : entity + "." + key;
		}
	    /**
	     * 拼接多个like的过滤条件
	     * @param entity
	     * @param key
	     * @param param
	     * @return
	     */
		public static String contractBindSqlConditionLike(String entity,String key,String param) {
			if (StringUtil.isEmpty(key)) {
				return "";
			}
			return " OR " + contractBindSql(entity, key) + " LIKE '" + like(param)+"'";
		}
		/**
	     * 拼接单个like的过滤条件
	     * @param entity
	     * @param key
	     * @param param
	     * @return
	     */
		public static String contractLike(String entity,String key,String param) {
			if (StringUtil.isEmpty(key)) {
				return "";
			}
			return contractBindSql(entity, key) + " LIKE '" + like(param)+"'";
		}
		
		/**
		 * 将参数强制转换为数据库中的数字类型
		 * @param param
		 * @return
		 */
		public static String changeToNumeric(String param) {
			if (StringUtil.isEmpty(param)) {
				return "";
			}
			if (isOracle) {
				return changeJdbcType(param, "TO_NUMBER",null);
			}
			return changeJdbcType(param, "CONVERT","SIGNED");
		}
		
		/**
		 * 将参数强制转换为数据库中的日前类型
		 * @param param
		 * @return
		 */
		public static String changeToDate(String param) {
			if (StringUtil.isEmpty(param)) {
				return "";
			}
			if (isOracle) {
				return changeJdbcType(param, "TO_DATE","'yyyy-MM-dd'");
			}
			return changeJdbcType(param, "str_to_date", "'%Y-%m-%d'");
		}
		
		/**
		 * 将参数强制转换为数据库中的日前类型
		 * @param param
		 * @return
		 */
		public static String changeToTime(String param) {
			if (StringUtil.isEmpty(param)) {
				return "";
			}
			if (isOracle) {
				return changeJdbcType(param, "TO_DATE","'HH:mm:ss'");
			}
			return changeJdbcType(param, "str_to_date", "'%T'");
		}
		
		/**
		 * 将参数强制转换为数据库中的日期类型
		 * @param param
		 * @return
		 */
		public static String changeToDateTime(String param) {
			if (StringUtil.isEmpty(param)) {
				return "";
			}
			if (isOracle) {
				return changeJdbcType(param, "TO_DATE","'yyyy-MM-dd HH:mm:ss'");
			}
			return changeJdbcType(param, "str_to_date", "'%Y-%m-%d %T'");
		}
		/**
		 * 数据库加一天
		 * @param param
		 * @return
		 */
		public static String addDay(String days,String sql) {
			if (StringUtil.isEmpty(days)) {
				days = "1";
			}
			return addTimeStamp(days + " day", sql);
		}
		/**
		 * 数据库添加时间戳
		 * @param param
		 * @return
		 */
		public static String addTimeStamp(String type,String sql) {
			if (StringUtil.isEmpty(type)) {
				return sql;
			}
			if (isOracle) {
				return sql + " +1 ";
			}
			return changeJdbcType(sql,"DATE_ADD","interval "+type);
		}
		
		/**
		 * 将参数强制转换为数据库中的字符串类型
		 * @param param
		 * @return
		 */
		public static String changeToVarchar(String param) {
			if (StringUtil.isEmpty(param)) {
				return "";
			}
			if (isOracle) {
				return changeJdbcType(param, "TO_CHAR",null);
			}
			return changeJdbcType(param, "CONCAT","''");
		}
		
		/**
		 * 将数据的日期格式格式化为字符串类型
		 * @param param （yyyy-MM-dd）
		 * @return
		 */
		public static String changeDateToVarchar(String param) {
			if (StringUtil.isEmpty(param)) {
				return "";
			}
			return changeDateToVarchar(param, "'%Y-%m-%d'", "'yyyy-MM-dd'");
		}
		
		/**
		 * 将数据的日期格式格式化为字符串类型
		 * @param param
		 * @param mType
		 * @param oType
		 * @return
		 */
		public static String changeDateToVarchar(String param,String mType,String oType) {
			if (StringUtil.isEmpty(param)) {
				return "";
			}
			if (isOracle) {
				return changeJdbcType(param, "TO_CHAR",oType);
			}
			return changeJdbcType(param, "DATE_FORMAT",mType);
		}
		/**
		 * 将数据的日期格式格式化为字符串类型
		 * @param param
		 * @return
		 */
		public static String changeTimeToVarchar(String param) {
			if (StringUtil.isEmpty(param)) {
				return "";
			}
			return changeDateToVarchar(param, "'%T'", "'HH:mm:ss'");
		}
		
		/**
		 * 将数据的日期格式格式化为字符串类型
		 * @param param
		 * @return
		 */
		public static String changeDateTimeToVarchar(String param) {
			if (StringUtil.isEmpty(param)) {
				return "";
			}
			return changeDateToVarchar(param, "'%Y-%m-%d %T'", "'yyyy-MM-dd HH:mm:ss'");
		}
		
		/**
		 * 强制改变参数的数据类型
		 * @param param
		 * @param type
		 * @param parseType
		 * @return
		 */
		public static String changeJdbcType(String param,String type,String parseType) {
			if (StringUtil.isEmpty(param)) {
				return "";
			}
			String joinPart =  StringUtil.isEmpty(parseType) ? ")" : ","+parseType+")";
			return type + "(" + param + joinPart;
		}
		
		/**
		 * 添加通配符
		 * @param condition
		 * @return
		 */
	    public static String like(String condition){
	    	if("".equals(condition)||condition==null) return null;
	    	return "%"+condition+"%";
	    }
	    
	    /**
	     * 将对象所有的字符串类型由Null改为空字符串
	     * @param o
	     * @return
	     */
	    public static Object  changeToNotNull(Object o) {
			Class<? extends Object> c = o.getClass();
			try {
				Field[] fs = c.getDeclaredFields();
				for (Field f : fs) {
					f.setAccessible(true);
					String st = f.get(o) + "";
					String str = st.replaceAll(" ", "");
					if (str == null || "null".equals(str)) {
						if (f.getType() == String.class) {
							f.set(o, "");
						}
					}
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return o;
		}
	    
	    /**
	     * 将所有字母大写
	     * @param str
	     * @return
	     */
	    public static String getUpperStr(String str) {
	    	if (StringUtil.isEmpty(str)) {
	    		return null;
	    	}
	    	return str.toUpperCase().replace(" ", "");
	    }
	    
	    /**
	     * 将参数改为数据库可识别的字符串类型
	     * @param str
	     * @return
	     */
	    public static String changeToString(String str) {
	    	if (StringUtil.isEmpty(str)) {
	    		return "";
	    	}
	    	return "'"+str+"'";
	    }
	    
	    /**
	     * 获得当前时间
	     * @return
	     */
	    public static String getNewDate() {
	    	return getNewDate("yyyy-MM-dd");
	    }
	    /**
	     * 获得当前时间
	     * @return
	     */
	    public static String getNewDate(String patten) {
	    	SimpleDateFormat format = new SimpleDateFormat(patten);
	    	return format.format(new Date());
	    }
	    /**
	     * 获得当前时间
	     * @return
	     */
	    public static String getNewDateTime() {
	    	return getNewDate("yyyy-MM-dd HH:mm:ss");
	    }
	    /**
	     * 获得动态默认数据（#{value}）
	     * @param key
	     * @return
	     */
	    public static String getSqlDefaultValue(String key) {
	    	if (StringUtil.isEmpty(key)) {
	    		return "";
	    	}
	    	return "#{"+key+"}";
	    }
}
